package com.aye.notepad;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.aye.notepad.DatabaseModel.Record;

import java.util.List;

public class MyAdapter extends BaseAdapter{
    private static final String TAG = "MyAdapter";
    //使用list<Nate>,list会存储数据库中note表所有记录。
    private List<Record> list;
    //用于将某个布局转换为view的对象。
    private LayoutInflater layoutInflater;
    //当创建MyAdapter对象的时候，需要list的数据
    public MyAdapter(List<Record> list, Context context){
        this.list=list;
        layoutInflater=LayoutInflater.from(context);
    }

    @Override
    public int getCount() {  //item加载项数
        return list.size();  //返回item的元素个数
    }

    @Override
    public Object getItem(int position) {
        //list.get(position)获取到的时Note对象，Note对象对应这表中的某条记录。
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        //id一般和position对应，所以返回position
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView==null){
            convertView=layoutInflater.inflate(R.layout.list_record,null,false);
            viewHolder=new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else {
            viewHolder=(ViewHolder)convertView.getTag();
        }
        //将数据库中的内容加载到对应的控件上
        Record record= (Record) getItem(position);
        viewHolder.tv_content.setText(record.getContent());
        viewHolder.tv_time.setText(record.getDate());
        viewHolder.tv_title.setText(record.getTitle());
        Log.i(TAG, "getView: "+record.toString());
        return convertView;
    }
    //用于给item的视图加载数据内容。
    class ViewHolder{
        TextView tv_content,tv_time,tv_title;
        public ViewHolder(View view){
            tv_content=view.findViewById(R.id.tv_content);
            tv_time=view.findViewById(R.id.tv_time);
            tv_title=view.findViewById(R.id.tv_title);
        }
    }
}

